package chatServer;

import java.net.MalformedURLException;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class ServerStarter extends Application{
	ChatServerImpl server = ChatServerImpl.getInstance();
	TextArea taDisplay;
	@Override
	public void start(Stage primaryStage) throws Exception {
		try {
			LocateRegistry.createRegistry(1099);
		} catch (RemoteException e) {
			e.printStackTrace();
		}
		VBox root = new VBox();
		Button startBtn = new Button("启动服务器");
		Button stopBtn = new Button("关闭服务器");
		startBtn.setLayoutX(50);startBtn.setLayoutY(50);
		stopBtn.setLayoutX(50);stopBtn.setLayoutY(80);
		stopBtn.setOnAction(new EventHandler<ActionEvent>() {

			@Override
			public void handle(ActionEvent event) {
				try {
					server.stop();
				} catch (RemoteException e) {
					e.printStackTrace();
				} catch (MalformedURLException e) {
					e.printStackTrace();
				} catch (NotBoundException e) {
					e.printStackTrace();
				}
			}
		});
		startBtn.setOnAction(new EventHandler<ActionEvent>() {
			
			@Override
			public void handle(ActionEvent event) {
				startAction();
			}
		});
		taDisplay = new TextArea();
		taDisplay.setEditable(false);
		root.getChildren().addAll(startBtn, stopBtn, taDisplay);
		Scene scene = new Scene(root,400,400);
		primaryStage.setScene(scene);
		primaryStage.setTitle("wetalkServer!");
		primaryStage.setResizable(true);
		primaryStage.show();
		primaryStage.setOnCloseRequest(e ->{
			exit();
		});
	}
	
	public static void main(String[] args) {
		launch(args);
	}
	
	private void exit() {
		try {
			server.stop();
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.exit(0);
	}
	
	public void startAction(){
		taDisplay.setText("");
		try {
			server.start();
			taDisplay.setText("服务器已启动");
		} catch (RemoteException e) {
			e.printStackTrace();
			taDisplay.setText("服务器启动失败");
		} catch (MalformedURLException e) {
			e.printStackTrace();
			taDisplay.setText("服务器启动失败");
		}
	}
	
	public void stopAction(){
		try {
			server.stop();
		} catch (RemoteException e) {
			e.printStackTrace();
			taDisplay.appendText("服务器停止错误\n");
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (NotBoundException e) {
			e.printStackTrace();
		}
	}

}
